package com.cqjtu.drive.service.impl;

import com.cqjtu.drive.mapper.VehicleMapper;
import com.cqjtu.drive.pojo.Vehicle;
import com.cqjtu.drive.response.Response;
import com.cqjtu.drive.service.VehicleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class VehicleServiceImpl implements VehicleService {

    @Autowired
    private VehicleMapper vehicleMapper;

    @Override
    public Response<Vehicle> getVehicleById(String vehicleId) {
        Vehicle vehicle = vehicleMapper.getVehicleById(vehicleId);
        if (vehicle != null) {
            return new Response<>(true, "Vehicle found", vehicle);
        } else {
            return new Response<>(false, "Vehicle not found");
        }
    }

    @Override
    public Response<String> insertVehicle(Vehicle vehicle) {
        try {
            List<Vehicle> list = vehicleMapper.getAllVehicles();
            if(list != null && !list.isEmpty()){
                String vId = Integer.toString(Integer.parseInt(list.get(list.size() - 1).getvId()) + 1);
                vehicle.setvId(vId);
            }else{
                vehicle.setvId("1");
            }

            vehicleMapper.insertVehicle(vehicle);
            return new Response<>(true, "Vehicle inserted successfully");
        } catch (Exception e) {
            return new Response<>(false, "Failed to insert vehicle: " + e.getMessage());
        }
    }

    @Override
    public Response<String> updateVehicle(Vehicle vehicle) {
        try {
            vehicleMapper.updateVehicle(vehicle);
            return new Response<>(true, "Vehicle updated successfully");
        } catch (Exception e) {
            return new Response<>(false, "Failed to update vehicle: " + e.getMessage());
        }
    }

    @Override
    public Response<String> deleteVehicle(String vehicleId) {
        try {
            vehicleMapper.deleteVehicle(vehicleId);
            return new Response<>(true, "Vehicle deleted successfully");
        } catch (Exception e) {
            return new Response<>(false, "Failed to delete vehicle: " + e.getMessage());
        }
    }

    @Override
    public Response<List<Vehicle>> getAllVehicles() {
        List<Vehicle> vehicles = vehicleMapper.getAllVehicles();
        if (vehicles != null && !vehicles.isEmpty()) {
            return new Response<>(true, "Vehicles retrieved successfully", vehicles);
        } else {
            return new Response<>(false, "No vehicles found");
        }
    }

    @Override
    public Response<List<Vehicle>> getVehiclesByname(String vName) {
        List<Vehicle> vehicles = vehicleMapper.getVehiclesByname(vName);
        if (vehicles != null && !vehicles.isEmpty()) {
            return new Response<>(true, "Vehicles retrieved successfully", vehicles);
        } else {
            return new Response<>(false, "No vehicles found");
        }
    }


}
